<template>
	<view>
		<template v-if="totalSpace !== 0">
			<view class="diskmemoro">
				<view class="diskmemoro-1">剩余{{((remainSpace/totalSpace)*100).toFixed(2)}}%</view>
				<view class="diskmemoro-circle">
					<!-- <view class="diskmemoro-circle-inner" :style="{height:25+'vw'}"></view> -->
					<view class="diskmemoro-circle-inner" :style="{height:((remainSpace/totalSpace)*40).toFixed(2)+'vw'}"></view>
				</view>
				<view class="diskmemoro-2">已用{{(((totalSpace-remainSpace)/totalSpace)*100).toFixed(2)}}%</view>
			</view>
			
			<j-cell title="存储容量" :tips="conversion(totalSpace)" :more="false"></j-cell>
			<j-cell title="录像分区" :tips="conversion(dirverType0)" :more="false"></j-cell>
			<j-cell title="图片分区" :tips="conversion(dirverType4)" :more="false"></j-cell>
			<j-cell title="剩余容量" :tips="conversion(remainSpace)" :more="false"></j-cell>
			<j-cell title="录像满时" :more="false">
				<view slot="tips" style="padding-left:20rpx">
					<uni-data-checkbox mode="tag" v-model="overWrite" :localdata="overWriteList" @change="change"></uni-data-checkbox>
				</view>
			</j-cell>
			<view class="bottom-fixed">
				<button type="default" class="block" @tap="onFormat">格式化</button>
			</view>
		</template>
		<template v-else>
			<view class="empty">
			    <view>
					<uni-icons custom-prefix="iconfont" type="icon-kong" size="64"></uni-icons>
			        <view>暂无SD卡</view>
			    </view>
			</view>
		</template>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				token: '',
				percent:0,
				/** 所有分区的TotalSpace和为0表示没有SD卡 */ 
				StorageInfo:[],
				// 总存储容量
				totalSpace:0,
				// 剩余容量
				remainSpace:0,
				// 录像分区
				dirverType0:0,
				// 图片分区
				dirverType4:0,
				// Manager组件配置-录像满时
				general:{},
				overWrite: 0,
				overWriteList: [{
					text: '停止录像',
					mode:'StopRecord',
					value: 0
				}, {
					text: '循环录像',
					mode:'OverWrite',
					value: 1
				}],
				
				iIndex: 0,
				jIndex: 0
			};
		}
		/**
		 * 生命周期函数--监听页面加载
		 */
		,
		onLoad: function(options) {
			console.log('=== StorageInfo:', options);
			this.token = options.token
		},
		/**
		 * 生命周期函数--监听页面初次渲染完成
		 */
		onReady: function() {},
		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow: function() {
			this.getinfo();
			this.getconfig()
		},
		/**
		 * 生命周期函数--监听页面隐藏
		 */
		onHide: function() {},
		/**
		 * 生命周期函数--监听页面卸载
		 */
		onUnload: function() {},
		/**
		 * 页面相关事件处理函数--监听用户下拉动作
		 */
		onPullDownRefresh: function() {},
		/**
		 * 页面上拉触底事件的处理函数
		 */
		onReachBottom: function() {},
		/**
		 * 用户点击右上角分享
		 */
		onShareAppMessage: function() {},
		methods: {
			// 获取磁盘信息
			getinfo() {
				uni.showLoading();
				let token = this.token;
				let data = {
					Name: 'StorageInfo'
				};
				getApp().globalData.api.getinfo(data, token, (result) => {
					uni.hideLoading()
					console.log('====================获取信息：', result);
					this.StorageInfo = result['StorageInfo'] || []
					console.log(this.StorageInfo)
					this.totalSpace=0;
					this.remainSpace=0;
					this.dirverType0 = 0;
					this.dirverType4 = 0;
					this.StorageInfo.forEach(item => {
						item.Partition.forEach((pro,index) => {
							// 读写
							if(pro.DirverType === 0){
								this.totalSpace += Number(parseInt(pro.TotalSpace,16).toString(10))
								this.remainSpace += Number(parseInt(pro.RemainSpace,16).toString(10))
								this.dirverType0 +=  Number(parseInt(pro.TotalSpace,16).toString(10))
							}
							// 只读
							else if(pro.DirverType === 1){
								// TODO
							}
							// 冗余
							else if(pro.DirverType === 3){
								// TODO
							}
							// 快照
							else if(pro.DirverType === 4){
								this.totalSpace += Number(parseInt(pro.TotalSpace,16).toString(10))
								this.remainSpace += Number(parseInt(pro.RemainSpace,16).toString(10))
								this.dirverType4 += Number(parseInt(pro.TotalSpace,16).toString(10))
							}
						})
					})
				});
			},
			// 获取General-硬盘满时处理策略
			getconfig() {
			    uni.showLoading();
			    let token = this.token;
			    let data = {
			        Name: 'General.General'
			    };
			    getApp().globalData.api.getconfig(data, token, (result) => {
			        uni.hideLoading()
			        console.log('====================获取配置：', result);
					this.general = result['General.General'] || {}
					if(this.general && this.general.OverWrite){
						this.overWrite = this.enumeration(this.general.OverWrite)
					}
			    });
			},
			// 设置General-硬盘满时处理策略
			setconfig() {
			    uni.showLoading();
			    let token = this.token;
			    let data = {
			        Name: 'General.General',
					'General.General':this.general
			    };
			    getApp().globalData.api.setconfig(data, token, (result) => {
			        uni.hideLoading()
			        console.log('====================设置配置：', result);
			    });
			},
			change(ev){
				if(ev.detail.value === 0){
					this.overWrite = 0
				}else if(ev.detail.value === 1){
					this.overWrite = 1
				}
				this.general.OverWrite = this.overWriteList[this.overWrite].mode
				this.setconfig()
			},
			// 格式化磁盘事件
			onFormat(){
				uni.showModal({
					title:'提示',
					content:'确认格式化磁盘？',
					success: (res) => {
						if(res.confirm){
							uni.showLoading({
								title:'格式化中...'
							})
							this.iIndex = 0
							this.jIndex = 0
							let arr = []; 
							if (this.iIndex < this.StorageInfo.length && this.jIndex < this.StorageInfo[this.iIndex].Partition.length) {
								console.log(this.iIndex,this.jIndex)
								this.StorageInfo.forEach((item,index)=>{
									item.Partition.forEach((ele,eleindex)=>{
										arr.push(this.OPStorageManager(index,eleindex))
									})
								})
								Promise.all(arr)
								    .then(res => {
								        console.log(res,'成功几次');
										uni.hideLoading();
										this.getinfo()
								        // loading.close();
								    })
								    .catch(err => {
								       //  loading.close();
								        console.log("error", err);
								    });
								// this.OPStorageManager(this.iIndex,this.jIndex)
							}
						}
					}
				})
			},
			OPStorageManager(i,j){
			   return new Promise((resolve, reject) => {
				   let token = this.token;
				   let data = {
				   	Name: 'OPStorageManager',
				   	OPStorageManager: {
				   		Action:'Clear',
				   		SerialNo:i,
				   		PartNo:j
				   	}
				   };
				   getApp().globalData.api.opdev(data, token, (result) => {
					resolve(result);//数据传递到下一个promise
				   });
			    });
			},
			// // 格式化磁盘
			// OPStorageManager(i,j){
			// 	let token = this.token;
			// 	let data = {
			// 		Name: 'OPStorageManager',
			// 		OPStorageManager: {
			// 			Action:'Clear',
			// 			SerialNo:i,
			// 			PartNo:j
			// 		}
			// 	};
			// 	getApp().globalData.api.opdev(data, token, (result) => {
			// 		console.log('====================设备操作：', result);
			// 		this.await()
			// 		this.getinfo()
			// 	});
			// },
			/**
			 * @description 顺序异步执行函数
			 */
			await(){
				this.jIndex = this.jIndex + 1;
				if (this.jIndex >= this.StorageInfo[this.iIndex].Partition.length) {
					this.jIndex = 0;
					this.iIndex = this.iIndex + 1
					
					if (this.iIndex　>= this.StorageInfo.length ){
						//已经结束
						uni.hideLoading()
					}else{
						this.OPStorageManager(this.iIndex,this.jIndex)
					}
				}else{
					this.OPStorageManager(this.iIndex,this.jIndex)
				}
			},
			/**
			 * @description 容量转换
			 * @param {Number} value 多少M容量
			 */
			conversion(value){
				if(value < 1){
					return `${(value*1024).toFixed(2)} KB`
				}else if(value >= 1 && value < 1024){
					return `${(value).toFixed(2)} MB`
				}else{
					return `${(value/1024).toFixed(2)} GB`
				}
				return 'error'
			},
			/**
			 * @description 根据返回的值获取overWriteList集合中的value值
			 * @param {String} value OverWrite模式
			 */
			enumeration(value){
				for (let i = 0; i < this.overWriteList.length; i++) {
					if(this.overWriteList[i].mode === value){
						return this.overWriteList[i].value
						break
					}
				}
			}
		}
	};
</script>

<style>
	.diskmemoro {
		background: #41c4bf;
		width: 100vw;
		height: 40vh;
		overflow: hidden;
		position: relative;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.diskmemoro-1 {
		position: absolute;
		top: 5vh;
		right: 20vw;
		color: #FFFFFF;
		font-size: 24rpx;
	}

	.diskmemoro-2 {
		position: absolute;
		bottom: 5vh;
		right: 20vw;
		color: #FFFFFF;
		font-size: 24rpx;
	}

	.diskmemoro-circle {
		width: 40vw;
		height: 40vw;
		border-radius: 100%;
		border: 1px solid #FFFFFF;
		background: #89BBF0;
		overflow: hidden;
	}

	.diskmemoro-circle-inner {
		width: 40vw;
		background: #FFFFFF;
	}
</style>
